package logger

import (
	"fmt"
	"os"
	"path"
	"regexp"
	"strings"
	"time"
)

var (
	formatRegexp = regexp.MustCompile(`%([YMDhmsqw])`)
)

func build(output string) string {
	file := format(output)
	dir := path.Dir(file)
	os.MkdirAll(dir, os.ModePerm)
	return file
}

func spec(output string) string {
	indexes := formatRegexp.FindAllStringIndex(output, -1)
	var expr = `0 * * * * ?`
	var level = -1
	for _, slice := range indexes {
		i, j := slice[0], slice[1]
		switch output[i:j] {
		case `%Y`: // 年
			if level < 1 {
				expr = `0 0 0 0 0 ?`
				level = 1
			}
		case `%M`: // 月
			if level < 2 {
				level = 2
				expr = `0 0 0 0 * ?`
			}
		case `%D`: // 日
			if level < 3 {
				level = 3
				expr = `0 0 0 * * ?`
			}
		case `%h`: // 时
			if level < 4 {
				level = 4
				expr = `0 0 * * * ?`
			}
		case `%m`: // 分
			if level < 5 {
				level = 5
				expr = `0 * * * * ?`
			}
		case `%s`: // 秒
			return `* * * * * ?`
		}
	}
	return expr
}

// %Y%M%D%h%m%s%q%w
func format(output string) string {
	now := time.Now()
	indexes := formatRegexp.FindAllStringIndex(output, -1)
	var list []string
	var last = 0
	for _, slice := range indexes {
		i, j := slice[0], slice[1]
		list = append(list, output[last:i])
		last = j
		switch output[i:j] {
		case `%Y`: // 年
			list = append(list, fmt.Sprintf(`%d`, now.Year()))
		case `%M`: // 月
			list = append(list, fmt.Sprintf(`%02d`, now.Month()))
		case `%D`: // 天
			list = append(list, fmt.Sprintf(`%02d`, now.Day()))
		case `%h`: // 时
			list = append(list, fmt.Sprintf(`%02d`, now.Hour()))
		case `%m`: // 分
			list = append(list, fmt.Sprintf(`%02d`, now.Minute()))
		case `%s`: // 秒
			list = append(list, fmt.Sprintf(`%02d`, now.Second()))
		case `%q`: // 季
			list = append(list, fmt.Sprintf(`%02d`, (int(now.Month())+2)/3))
		case `%w`: // 周
			list = append(list, fmt.Sprintf(`%02d`, now.Weekday()))
		}
	}
	list = append(list, output[last:])
	return strings.Join(list, ``)
}
